package com.cx330;

import lombok.Getter;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class Example91_02 {
    public static void main(String[] args) {
        RealAdminServiceOne02 one = new RealAdminServiceOne02(); // 被代理对象
        AdminServiceOne02 proxyOne = DynamicProxyTemplate.createProxy(one); // 代理类对象
        proxyOne.adminOperationOne();

        RealAdminServiceTwo02 two = new RealAdminServiceTwo02(); // 被代理对象
        AdminServiceTwo02 proxyTwo = DynamicProxyTemplate.createProxy(two); // 代理类对象
        proxyTwo.adminOperationTwo();
    }
}

interface AdminServiceOne02 { // 主题接口1
    void adminOperationOne();
}

interface AdminServiceTwo02 { // 主题接口2
    void adminOperationTwo();
}

class DynamicProxyTemplate implements InvocationHandler {
    private Object target;

    public DynamicProxyTemplate(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 前置处理
        System.out.println("前置处理操作（例如：事务开启）");
        // 权限校验，执行被代理类的方法
        Object result = null;
        String user = Session02.getUser();
        if ("admin".equals(user)) {
            System.out.println(user + "请求的操作被允许！");
            // 调用被代理类的方法
            result = method.invoke(target, args);
        } else {
            System.out.println(user = "请求的操作被拒绝");
        }
        // 后置处理
        System.out.println("后置处理操作（例如：事务提交）");
        return result;
    }

    public static <T> T createProxy(T target) {
        return (T) Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new DynamicProxyTemplate(target));
    }
}

class RealAdminServiceOne02 implements AdminServiceOne02 { // 被代理类1
    @Override
    public void adminOperationOne() {
        System.out.println("执行具体业务操作1");
    }
}

class RealAdminServiceTwo02 implements AdminServiceTwo02 { // 被代理类2
    @Override
    public void adminOperationTwo() {
        System.out.println("执行具体业务操作2");
    }
}

class Session02 {
    @Getter
    public static String user = "admin";
}